package cn.iocoder.yudao.module.trade.order.service.handler;

import cn.iocoder.yudao.module.api.product.sku.ProductSkuApi;
import cn.iocoder.yudao.module.api.trade.order.enums.TradeOrderTypeEnum;
import cn.iocoder.yudao.module.trade.order.convert.TradeOrderConvert;
import cn.iocoder.yudao.module.trade.order.dal.dataobject.TradeOrderDO;
import cn.iocoder.yudao.module.trade.order.dal.dataobject.TradeOrderItemDO;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

import static java.util.Collections.singletonList;

/**
 // TODO 团购订单不应该杂糅进购物订单，后续考虑抽象出通用的交易订单及交易订单扩展，以便关联具体的业务订单数据
 * 产品 SKU 库存及销量的 {@link TradeOrderHandler} 实现类
 *
 * @author 芋道源码
 */
@Component
public class TradeProductSkuOrderHandler implements TradeOrderHandler {

    @Resource
    private ProductSkuApi productSkuApi;

    @Override
    public void beforeOrderCreate(TradeOrderDO order, List<TradeOrderItemDO> orderItems) {
        if (!Objects.equals(order.getType(), TradeOrderTypeEnum.GROUPON.getType())) {
            // 订单创建前（数据存入数据库前）扣减库存
            productSkuApi.updateSkuStock(TradeOrderConvert.INSTANCE.convertNegative(orderItems));
        }
    }

    @Override
    public void afterCancelOrder(TradeOrderDO order, List<TradeOrderItemDO> orderItems) {
        if (!Objects.equals(order.getType(), TradeOrderTypeEnum.GROUPON.getType())) {
            // 售后的订单项，已经在 afterCancelOrderItem 回滚库存，所以这里不需要重复回滚
            orderItems = filterOrderItemListByNoneAfterSale(orderItems);
            productSkuApi.updateSkuStock(TradeOrderConvert.INSTANCE.convert(orderItems));
            if (Boolean.TRUE.equals(order.getPayStatus())) {
                productSkuApi.updateSkuSalesCount(TradeOrderConvert.INSTANCE.convertNegative(orderItems));
            }
        }
    }

    @Override
    public void afterCancelOrderItem(TradeOrderDO order, TradeOrderItemDO orderItem) {
        if (!Objects.equals(order.getType(), TradeOrderTypeEnum.GROUPON.getType())) {
            // 订单取消后返还库存、扣减销量
            productSkuApi.updateSkuStock(TradeOrderConvert.INSTANCE.convert(singletonList(orderItem)));
            if (Boolean.TRUE.equals(order.getPayStatus())) {
                productSkuApi.updateSkuSalesCount(TradeOrderConvert.INSTANCE.convertNegative(singletonList(orderItem)));
            }
        }
    }

    @Override
    public void afterPayOrder(TradeOrderDO order, List<TradeOrderItemDO> orderItems) {
        if (!Objects.equals(order.getType(), TradeOrderTypeEnum.GROUPON.getType())) {
            // 订单支付成功后增加销量
            productSkuApi.updateSkuSalesCount(TradeOrderConvert.INSTANCE.convert(orderItems));
        }
    }

}
